package com.xmhmyh.generalframework.framework.yusngen;

import com.alibaba.fastjson.JSONObject;
import com.xmhmyh.generalframework.framework.redis.IredisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 于丁
 * @DateTime: 2020/3/10 3:15 下午
 */
@Slf4j
@Component
public class YuSnGenUtil {

    @Autowired
    private IredisService iredisService;

    private static final String KEY = "YUSNCONFIG:";

    /**
     * @Author: 于丁
     * @Description: 初始化流水号
     * @DateTime: 2020/3/10 3:16 下午
     * @Params:
     * @Return
     */
    public void init(List<YuSnGenCode> yuSnGenCodes) {
        // 流水号初始化入缓存
        for (YuSnGenCode yuSnGenCode : yuSnGenCodes) {
            String redisKey = yuSnGenCode.getEntity().getName();
            // 判断是不是已经加入缓存了
            iredisService.set(KEY + yuSnGenCode.getEntity().getName(), JSONObject.toJSONString(yuSnGenCode));
            log.info(yuSnGenCode.getEntity().getName() + "已初始化");

        }
    }

    /**
     * @Author: 于丁
     * @Description: 生成流水号
     * @DateTime: 2020/3/10 3:41 下午
     * @Params:
     * @Return
     */
    public Optional<String> gen(Class c) {
        String redisKey = KEY + c.getName();
        if (null != iredisService.get(redisKey)) {
            YuSnGenCode yuSnGenCode = JSONObject.parseObject(iredisService.get(redisKey).toString(), YuSnGenCode.class);

            if (iredisService.get(KEY + yuSnGenCode.getPrefix()) == null) {
                // 设置到第二天早上00：00：01过期
                Long todayTime = LocalDate.now().plusDays(1).atTime(0, 0, 0, 1).atOffset(ZoneOffset.ofHours(8)).toEpochSecond();
                Long nowTime = LocalDateTime.now().atOffset(ZoneOffset.ofHours(8)).toEpochSecond();
                Long expireTime = todayTime - nowTime;
                iredisService.set(KEY + yuSnGenCode.getPrefix(), 0, expireTime * 1000, TimeUnit.MILLISECONDS);
            }

            // 自增
            StringBuffer sn = new StringBuffer();
            sn.append(yuSnGenCode.getPrefix());
            String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            sn.append(date);
            Long num = iredisService.incr(KEY + yuSnGenCode.getPrefix());
            sn.append(addZero(String.valueOf(num), yuSnGenCode.getNum()));
            String random = String.valueOf(new Random().nextInt(1000));
            sn.append(random);
            return Optional.ofNullable(sn.toString());
        } else {
            log.error("【流水号生成错误】" + c.getName() + "未注册过流水号");
            return Optional.ofNullable(null);
        }
    }


    /**
     * @Author: 于丁
     * @Description: 自动补零
     * @DateTime: 2020/3/10 4:10 下午
     * @Params:
     * @Return
     */
    public String addZero(String numStr, Integer maxNum) {
        int addNum = maxNum - numStr.length();
        StringBuffer rStr = new StringBuffer();
        for (int i = 0; i < addNum; i++) {
            rStr.append("0");
        }
        rStr.append(numStr);
        return rStr.toString();
    }
}
